package com.example.lowbird.lowbird.fragment;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;


import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.PointerIconCompat;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.activeandroid.query.Delete;
import com.cjj.MaterialRefreshLayout;

import com.cjj.MaterialRefreshListener;
import com.example.lowbird.lowbird.R;
import com.example.lowbird.lowbird.activity.Buyactivity;
import com.example.lowbird.lowbird.activity.GoodActivity;
import com.example.lowbird.lowbird.activity.PayActivity;
import com.example.lowbird.lowbird.adapter.Shopadapter;
import com.example.lowbird.lowbird.constant.Contants;
import com.example.lowbird.lowbird.java.RecycleViewDivider;
import com.example.lowbird.lowbird.java.SHopcar;
import com.example.lowbird.lowbird.utils.Dbutils;
import com.example.lowbird.lowbird.utils.SpUtil;
import com.example.lowbird.lowbird.utils.ZhendongUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * <p>
 * to handle interaction events.
 * Use the {@link ShopingFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ShopingFragment extends Basefragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private static Context mContext;

    private static List<SHopcar> shopscars = new ArrayList<>();

    private static Shopadapter mShopadapter;


    static Button bt_shopset;

    static ListView lv_shop;


    static CheckBox cb_shopall;


    public static TextView tv_shopprice;

    static Button bt_shopbotton;
    @Bind(R.id.mrf_shop)
    MaterialRefreshLayout mrf_shop;

    public ShopingFragment() {
        // Required empty public constructor
    }


    public static ShopingFragment newInstance(String param1, String param2) {
        ShopingFragment fragment = new ShopingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
        mContext = getContext();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_shoping, container, false);
        lv_shop = ((ListView) view.findViewById(R.id.lv_shop));
        tv_shopprice = ((TextView) view.findViewById(R.id.tv_shopprice));
        view.findViewById(R.id.bt_shopset);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {

        initmrffresh();

        Log.e("SHOP", "onViewCreated: " + shopscars.size());
        cb_shopall = ((CheckBox) view.findViewById(R.id.cb_shopall));
        bt_shopset = ((Button) view.findViewById(R.id.bt_shopset));
        bt_shopbotton = ((Button) view.findViewById(R.id.bt_shopbotton));
        shopscars = Dbutils.getShopcar();
        mShopadapter = new Shopadapter(mContext, shopscars);
        lv_shop.setAdapter(mShopadapter);
        initlistdata();
        initlvlisten();

    }

    private void initlvlisten() {

        final GestureDetector ges = new GestureDetector(mContext, new GestureDetector.OnGestureListener() {
            @Override
            public boolean onDown(MotionEvent e) {
                Log.e("SHOP", "1onDown: " + "Ss");
                return false;
            }

            @Override
            public void onShowPress(MotionEvent e) {
                Log.e("SHOP", "2onDown: " + "Ss");

            }

            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                Log.e("SHOP", "3onDown: " + "Ss");
                return false;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                Log.e("SHOP", "4onDown: " + "Ss");
                return false;
            }

            @Override
            public void onLongPress(MotionEvent e) {
                Log.e("SHOP", "5onDown: " + "Ss");

            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                Log.e("SHOP", "6onDown: " + "Ss");
                return false;
            }
        });


        lv_shop.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                ges.onTouchEvent(event);

                return false;
            }
        });

    }

    //重新加载购物车内容
    public static void initlistdata() {

        showprice();
        cb_shopall.setText("全选");
        cb_shopall.setChecked(false);


    }

    //计算总价格
    public static void showprice() {

        float totalprice = 0;
        shopscars = Dbutils.getShopcar();
        mShopadapter.changdata(shopscars);

        for (int i = 0; i < shopscars.size(); i++) {
            SHopcar sHopcar = shopscars.get(i);
            totalprice += sHopcar.getPrice() * sHopcar.getCount();
        }

        tv_shopprice.setText(totalprice + "");

    }

    private void initmrffresh() {

        mrf_shop.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {

                new Thread() {
                    @Override
                    public void run() {

                        try {
                            sleep(500);

                            mrf_shop.post(new Runnable() {
                                @Override
                                public void run() {

                                    initlistdata();


                                }
                            });
                            mrf_shop.finishRefresh();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }.start();

            }


        });

    }


    @OnClick({R.id.bt_shopbotton, R.id.bt_shopset, R.id.cb_shopall})
    public void onClick(View view) {

        switch (view.getId()) {


            case R.id.bt_shopbotton:

                Log.e("SHOP", "onClickall: " + "点击了shop");

                setbuyordelete();

                break;

            case R.id.bt_shopset:

                setshopcar();

                Log.e("SHOP", "onClick: " + "点击了shop");

                break;

            case R.id.cb_shopall:
                setcbchecked();
                break;

            default:
                Log.e("SHOP", "onClick: " + "点击了more");
                break;


        }


    }

    private void setbuyordelete() {

        shopscars = Dbutils.getShopcar();
        String bts = bt_shopbotton.getText().toString();
        boolean buy = false;

        for (int i = 0; i < shopscars.size(); i++) {
            SHopcar sHopcar = shopscars.get(i);
            int selected = sHopcar.getSelected();
            if (selected == 2) {

                buy = true;

                break;

            }
            Log.e("SHOP", "setbuyordelete: " + i);
        }


        Log.e("SHOP", "setbuyordelete: " + bts);
        if (!buy) {

            Log.e("SHOP", "setbuyordelete:请选择购买的商品 ");
        } else if (bts.equals("去结算") ) {

            String string = SpUtil.getString(mContext, Contants.ifRLOGIN, "");

            if (string.equals("")){
                Intent intent=new Intent(mContext,PayActivity.class);

                startActivity(intent,true);

            }
            else{
                Intent intent=new Intent(mContext,PayActivity.class);
                startActivity(intent,false);

            }

            //TO结算
        } else if (bts.equals("删除")) {


            Log.e("SHOP", "setbuyordelete: " + lv_shop.getChildCount() + "shopcars" + shopscars.size());

            int selected;
            SHopcar sHopcar;
            for (int i = 0; i < shopscars.size(); i++) {


                sHopcar = shopscars.get(i);

                selected = sHopcar.getSelected();

                if (selected == 2) {
                    Dbutils.deletShop(sHopcar.getName());

                }


            }


            ShopingFragment.initlistdata();
            //TO删除

        }
    }

    private void setcbchecked() {
        String string = cb_shopall.getText().toString();
        if (string.equals("全选")) {

            cb_shopall.setText("全不选");
            for (int i = 0; i < shopscars.size(); i++) {


                Dbutils.updataCheck(shopscars.get(i).getName(), 2);


            }

        } else {
            cb_shopall.setText("全选");

            for (int i = 0; i < shopscars.size(); i++) {
                Dbutils.updataCheck(shopscars.get(i).getName(), 1);


            }
        }


    }

    private void setshopcar() {
        String string = bt_shopset.getText().toString();
        ZhendongUtils.vSimple(mContext, 20);

        if (string.equals("编辑")) {

            bt_shopset.setText("完成");
            bt_shopbotton.setText("删除");


        } else if (string.equals("完成")) {
            bt_shopset.setText("编辑");
            bt_shopbotton.setText("去结算");

        }
    }
}
